#!/usr/bin/env bash

if [ ! -d portal ]
then
    mkdir portal -pv
fi

echo "remove current portal files."
cd portal
rm index.html -f
rm static -rf
cd ..

if [ ! -d ../portal ]
then
    echo "cannot found web portal project dir."
    exit 1
fi

cd ../portal
cnpm run build
if [ $? != 0 ]
then
    echo "build portal project failed."
    exit 2
fi
cd ../gateway

echo "remove current built files."
rm uenbiot.tar -f
rm uenbiot-* -f

echo "generate golang source files."
go generate
if [ $? != 0 ]
then
    echo "go generate failed."
    exit 3
fi

xgo -pkg=/build -ldflags="-s -w" -targets "linux/386,linux/amd64,linux/arm-7,linux/arm64,windows/*" .
if [ $? != 0 ]
then
    echo "xgo cross compile failed."
    exit 4
fi


rename 's/build/uenbiot/' build-*
if [ $? != 0 ]
then
    echo "rename build-* to uenbiot-* failed."
    exit 4
fi

gzip -9 uenbiot-*
if [ $? != 0 ]
then
    echo "gzip uenbiot-* failed."
    exit 4
fi

tar cvf uenbiot.tar *.gz
if [ $? != 0 ]
then
    echo "tar uenbiot.tar failed."
    exit 4
fi

echo "build completed."

